<template>
  <div class="inventory-records">
    <div class="page-header">
      <h2>出入库记录</h2>
      <div class="header-actions">
        <el-button type="primary" @click="showInboundDialog">
          <i class="el-icon-plus"></i> 新增入库
        </el-button>
        <el-button type="warning" @click="showOutboundDialog">
          <i class="el-icon-minus"></i> 新增出库
        </el-button>
        <el-button type="info" @click="exportRecords">
          <i class="el-icon-download"></i> 导出记录
        </el-button>
      </div>
    </div>
    
    <el-card shadow="hover" class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="SKU编码">
          <el-input v-model="filterForm.sku" placeholder="SKU编码" clearable></el-input>
        </el-form-item>
        <el-form-item label="SKU名称">
          <el-input v-model="filterForm.skuName" placeholder="SKU名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="记录类型">
          <el-select v-model="filterForm.recordType" placeholder="记录类型" clearable>
            <el-option label="入库" value="inbound"></el-option>
            <el-option label="出库" value="outbound"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="filterForm.operationType" placeholder="操作类型" clearable>
            <el-option label="采购入库" value="purchase"></el-option>
            <el-option label="退货入库" value="return"></el-option>
            <el-option label="销售出库" value="sale"></el-option>
            <el-option label="损耗出库" value="loss"></el-option>
            <el-option label="调拨" value="transfer"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card shadow="hover" class="table-card">
      <div class="table-operations">
        <span class="total-count">共 {{ total }} 条记录</span>
        <el-select v-model="batchAction" placeholder="批量操作" size="small" style="width: 120px">
          <el-option label="批量导出" value="export"></el-option>
          <el-option label="批量删除" value="delete"></el-option>
        </el-select>
        <el-button size="small" type="primary" :disabled="!selectedRecords.length" @click="handleBatchAction">
          执行
        </el-button>
      </div>
      
      <el-table
        :data="records"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="recordId" label="记录ID" width="100"></el-table-column>
        <el-table-column prop="recordType" label="记录类型" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.recordType === 'inbound' ? 'success' : 'danger'">
              {{ scope.row.recordType === 'inbound' ? '入库' : '出库' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operationType" label="操作类型" width="120">
          <template slot-scope="scope">
            <span>{{ getOperationTypeText(scope.row.operationType) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sku" label="SKU编码" width="150"></el-table-column>
        <el-table-column prop="skuName" label="SKU名称" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="quantity" label="数量" width="100">
          <template slot-scope="scope">
            <span :class="scope.row.recordType === 'inbound' ? 'inbound-quantity' : 'outbound-quantity'">
              {{ scope.row.recordType === 'inbound' ? '+' : '-' }}{{ scope.row.quantity }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="beforeStock" label="操作前库存" width="120"></el-table-column>
        <el-table-column prop="afterStock" label="操作后库存" width="120"></el-table-column>
        <el-table-column prop="operator" label="操作人" width="120"></el-table-column>
        <el-table-column prop="operationTime" label="操作时间" width="170"></el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="viewDetail(scope.row)">详情</el-button>
            <el-button size="mini" type="danger" @click="deleteRecord(scope.row)" v-if="canDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 入库对话框 -->
    <el-dialog title="新增入库记录" :visible.sync="inboundDialogVisible" width="50%">
      <el-form :model="inboundForm" :rules="inboundRules" ref="inboundForm" label-width="100px">
        <el-form-item label="SKU选择" prop="sku">
          <el-select
            v-model="inboundForm.sku"
            filterable
            remote
            reserve-keyword
            placeholder="请输入SKU编码或名称"
            :remote-method="searchSkus"
            :loading="searchingSkus"
            style="width: 100%"
            @change="handleSkuChange"
          >
            <el-option
              v-for="item in skuOptions"
              :key="item.sku"
              :label="`${item.sku} - ${item.name}`"
              :value="item.sku">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="当前库存" v-if="selectedSkuInfo">
          <span>{{ selectedSkuInfo.stock }}</span>
        </el-form-item>
        <el-form-item label="入库数量" prop="quantity">
          <el-input-number v-model="inboundForm.quantity" :min="1" :max="10000"></el-input-number>
        </el-form-item>
        <el-form-item label="入库类型" prop="operationType">
          <el-select v-model="inboundForm.operationType" placeholder="请选择入库类型" style="width: 100%">
            <el-option label="采购入库" value="purchase"></el-option>
            <el-option label="退货入库" value="return"></el-option>
            <el-option label="调拨入库" value="transfer"></el-option>
            <el-option label="其他入库" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作时间" prop="operationTime">
          <el-date-picker
            v-model="inboundForm.operationTime"
            type="datetime"
            placeholder="选择日期时间"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="操作人" prop="operator">
          <el-input v-model="inboundForm.operator" placeholder="请输入操作人"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="inboundForm.remark" :rows="3" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="inboundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitInbound">确定</el-button>
      </span>
    </el-dialog>
    
    <!-- 出库对话框 -->
    <el-dialog title="新增出库记录" :visible.sync="outboundDialogVisible" width="50%">
      <el-form :model="outboundForm" :rules="outboundRules" ref="outboundForm" label-width="100px">
        <el-form-item label="SKU选择" prop="sku">
          <el-select
            v-model="outboundForm.sku"
            filterable
            remote
            reserve-keyword
            placeholder="请输入SKU编码或名称"
            :remote-method="searchSkus"
            :loading="searchingSkus"
            style="width: 100%"
            @change="handleSkuChangeForOutbound"
          >
            <el-option
              v-for="item in skuOptions"
              :key="item.sku"
              :label="`${item.sku} - ${item.name}`"
              :value="item.sku">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="当前库存" v-if="selectedSkuInfo">
          <span>{{ selectedSkuInfo.stock }}</span>
        </el-form-item>
        <el-form-item label="出库数量" prop="quantity">
          <el-input-number v-model="outboundForm.quantity" :min="1" :max="selectedSkuInfo ? selectedSkuInfo.stock : 1"></el-input-number>
        </el-form-item>
        <el-form-item label="出库类型" prop="operationType">
          <el-select v-model="outboundForm.operationType" placeholder="请选择出库类型" style="width: 100%">
            <el-option label="销售出库" value="sale"></el-option>
            <el-option label="损耗出库" value="loss"></el-option>
            <el-option label="调拨出库" value="transfer"></el-option>
            <el-option label="其他出库" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作时间" prop="operationTime">
          <el-date-picker
            v-model="outboundForm.operationTime"
            type="datetime"
            placeholder="选择日期时间"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="操作人" prop="operator">
          <el-input v-model="outboundForm.operator" placeholder="请输入操作人"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="outboundForm.remark" :rows="3" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="outboundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitOutbound">确定</el-button>
      </span>
    </el-dialog>
    
    <!-- 记录详情对话框 -->
    <el-dialog title="记录详情" :visible.sync="recordDetailDialogVisible" width="50%">
      <div class="dialog-content" v-if="currentRecord">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="记录ID">{{ currentRecord.recordId }}</el-descriptions-item>
          <el-descriptions-item label="记录类型">
            <el-tag :type="currentRecord.recordType === 'inbound' ? 'success' : 'danger'">
              {{ currentRecord.recordType === 'inbound' ? '入库' : '出库' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="操作类型">{{ getOperationTypeText(currentRecord.operationType) }}</el-descriptions-item>
          <el-descriptions-item label="SKU编码">{{ currentRecord.sku }}</el-descriptions-item>
          <el-descriptions-item label="SKU名称">{{ currentRecord.skuName }}</el-descriptions-item>
          <el-descriptions-item label="数量">
            <span :class="currentRecord.recordType === 'inbound' ? 'inbound-quantity' : 'outbound-quantity'">
              {{ currentRecord.recordType === 'inbound' ? '+' : '-' }}{{ currentRecord.quantity }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="操作前库存">{{ currentRecord.beforeStock }}</el-descriptions-item>
          <el-descriptions-item label="操作后库存">{{ currentRecord.afterStock }}</el-descriptions-item>
          <el-descriptions-item label="操作人">{{ currentRecord.operator }}</el-descriptions-item>
          <el-descriptions-item label="操作时间">{{ currentRecord.operationTime }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ currentRecord.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="recordDetailDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'InventoryRecordsView',
  data() {
    return {
      loading: false,
      filterForm: {
        sku: '',
        skuName: '',
        recordType: '',
        operationType: '',
        dateRange: []
      },
      records: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      selectedRecords: [],
      batchAction: '',
      inboundDialogVisible: false,
      outboundDialogVisible: false,
      recordDetailDialogVisible: false,
      currentRecord: null,
      inboundForm: {
        sku: '',
        quantity: 1,
        operationType: 'purchase',
        operationTime: new Date(),
        operator: '',
        remark: ''
      },
      inboundRules: {
        sku: [
          { required: true, message: '请选择SKU', trigger: 'change' }
        ],
        quantity: [
          { required: true, message: '请输入入库数量', trigger: 'blur' }
        ],
        operationType: [
          { required: true, message: '请选择入库类型', trigger: 'change' }
        ],
        operationTime: [
          { required: true, message: '请选择操作时间', trigger: 'change' }
        ],
        operator: [
          { required: true, message: '请输入操作人', trigger: 'blur' }
        ]
      },
      outboundForm: {
        sku: '',
        quantity: 1,
        operationType: 'sale',
        operationTime: new Date(),
        operator: '',
        remark: ''
      },
      outboundRules: {
        sku: [
          { required: true, message: '请选择SKU', trigger: 'change' }
        ],
        quantity: [
          { required: true, message: '请输入出库数量', trigger: 'blur' }
        ],
        operationType: [
          { required: true, message: '请选择出库类型', trigger: 'change' }
        ],
        operationTime: [
          { required: true, message: '请选择操作时间', trigger: 'change' }
        ],
        operator: [
          { required: true, message: '请输入操作人', trigger: 'blur' }
        ]
      },
      skuOptions: [],
      searchingSkus: false,
      selectedSkuInfo: null
    }
  },
  created() {
    this.fetchRecords();
  },
  methods: {
    fetchRecords() {
      this.loading = true;
      // 模拟API请求
      setTimeout(() => {
        this.records = [
          {
            recordId: 'IN202305150001',
            recordType: 'inbound',
            operationType: 'purchase',
            sku: 'COMP-CPU-I5',
            skuName: 'Intel i5 处理器',
            quantity: 10,
            beforeStock: 5,
            afterStock: 15,
            operator: '张三',
            operationTime: '2023-05-15 09:30:22',
            remark: '采购入库'
          },
          {
            recordId: 'OUT202305150002',
            recordType: 'outbound',
            operationType: 'sale',
            sku: 'COMP-RAM-16G',
            skuName: '16GB DDR4 内存条',
            quantity: 5,
            beforeStock: 33,
            afterStock: 28,
            operator: '李四',
            operationTime: '2023-05-15 10:15:45',
            remark: '销售出库'
          },
          {
            recordId: 'IN202305150003',
            recordType: 'inbound',
            operationType: 'return',
            sku: 'COMP-SSD-512',
            skuName: '512GB SSD固态硬盘',
            quantity: 2,
            beforeStock: 8,
            afterStock: 10,
            operator: '王五',
            operationTime: '2023-05-15 11:20:18',
            remark: '退货入库'
          },
          {
            recordId: 'OUT202305150004',
            recordType: 'outbound',
            operationType: 'loss',
            sku: 'COMP-MB-Z590',
            skuName: 'Z590主板',
            quantity: 1,
            beforeStock: 6,
            afterStock: 5,
            operator: '赵六',
            operationTime: '2023-05-15 14:05:33',
            remark: '损耗出库'
          },
          {
            recordId: 'OUT202305150005',
            recordType: 'outbound',
            operationType: 'sale',
            sku: 'COMP-GPU-3060',
            skuName: 'NVIDIA RTX 3060显卡',
            quantity: 2,
            beforeStock: 5,
            afterStock: 3,
            operator: '张三',
            operationTime: '2023-05-15 16:40:12',
            remark: '销售出库'
          }
        ];
        this.total = 156;
        this.loading = false;
      }, 1000);
    },
    handleFilter() {
      this.currentPage = 1;
      this.fetchRecords();
    },
    resetFilter() {
      this.filterForm = {
        sku: '',
        skuName: '',
        recordType: '',
        operationType: '',
        dateRange: []
      };
      this.handleFilter();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchRecords();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchRecords();
    },
    handleSelectionChange(val) {
      this.selectedRecords = val;
    },
    handleBatchAction() {
      if (!this.batchAction) {
        this.$message.warning('请选择批量操作类型');
        return;
      }
      
      if (this.batchAction === 'export') {
        this.$message.success(`已开始导出${this.selectedRecords.length}条记录的数据`);
      } else if (this.batchAction === 'delete') {
        this.$confirm('确定要删除选中的记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message.success(`成功删除${this.selectedRecords.length}条记录`);
          this.fetchRecords();
        }).catch(() => {
          // 取消删除
        });
      }
    },
    getOperationTypeText(type) {
      const types = {
        purchase: '采购入库',
        return: '退货入库',
        sale: '销售出库',
        loss: '损耗出库',
        transfer: '调拨',
        other: '其他'
      };
      return types[type] || '未知';
    },
    showInboundDialog() {
      this.inboundDialogVisible = true;
      this.inboundForm = {
        sku: '',
        quantity: 1,
        operationType: 'purchase',
        operationTime: new Date(),
        operator: '',
        remark: ''
      };
      this.selectedSkuInfo = null;
    },
    showOutboundDialog() {
      this.outboundDialogVisible = true;
      this.outboundForm = {
        sku: '',
        quantity: 1,
        operationType: 'sale',
        operationTime: new Date(),
        operator: '',
        remark: ''
      };
      this.selectedSkuInfo = null;
    },
    searchSkus(query) {
      if (query) {
        this.searchingSkus = true;
        // 模拟搜索SKU
        setTimeout(() => {
          this.skuOptions = [
            { sku: 'COMP-CPU-I5', name: 'Intel i5 处理器', stock: 15 },
            { sku: 'COMP-RAM-16G', name: '16GB DDR4 内存条', stock: 28 },
            { sku: 'COMP-SSD-512', name: '512GB SSD固态硬盘', stock: 10 },
            { sku: 'COMP-MB-Z590', name: 'Z590主板', stock: 5 },
            { sku: 'COMP-GPU-3060', name: 'NVIDIA RTX 3060显卡', stock: 3 }
          ];
          this.searchingSkus = false;
        }, 500);
      } else {
        this.skuOptions = [];
      }
    },
    handleSkuChange(sku) {
      if (sku) {
        this.selectedSkuInfo = this.skuOptions.find(item => item.sku === sku);
      } else {
        this.selectedSkuInfo = null;
      }
    },
    handleSkuChangeForOutbound(sku) {
      this.handleSkuChange(sku);
      if (this.selectedSkuInfo) {
        // 重置出库数量，确保不超过库存
        this.outboundForm.quantity = Math.min(1, this.selectedSkuInfo.stock);
      }
    },
    submitInbound() {
      this.$refs.inboundForm.validate((valid) => {
        if (valid) {
          // 模拟提交
          setTimeout(() => {
            this.$message.success(`成功入库 ${this.inboundForm.quantity} 个 ${this.selectedSkuInfo.name}`);
            this.inboundDialogVisible = false;
            this.fetchRecords();
          }, 500);
        } else {
          return false;
        }
      });
    },
    submitOutbound() {
      this.$refs.outboundForm.validate((valid) => {
        if (valid) {
          if (!this.selectedSkuInfo) {
            this.$message.error('请选择SKU');
            return false;
          }
          
          if (this.outboundForm.quantity > this.selectedSkuInfo.stock) {
            this.$message.error('出库数量不能大于当前库存');
            return false;
          }
          
          // 模拟提交
          setTimeout(() => {
            this.$message.success(`成功出库 ${this.outboundForm.quantity} 个 ${this.selectedSkuInfo.name}`);
            this.outboundDialogVisible = false;
            this.fetchRecords();
          }, 500);
        } else {
          return false;
        }
      });
    },
    viewDetail(row) {
      this.currentRecord = row;
      this.recordDetailDialogVisible = true;
    },
    deleteRecord(row) {
      this.$confirm('确定要删除该记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success('记录删除成功');
        this.fetchRecords();
      }).catch(() => {
        // 取消删除
      });
    },
    canDelete(row) {
      // 判断记录是否可以删除，例如只允许删除当天的记录
      const today = new Date().toISOString().split('T')[0];
      const recordDate = row.operationTime.split(' ')[0];
      return recordDate === today;
    },
    exportRecords() {
      this.$message.success('记录导出成功');
    }
  }
}
</script>

<style scoped>
.inventory-records {
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.page-header h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}
.header-actions {
  display: flex;
  gap: 10px;
}
.filter-card {
  margin-bottom: 20px;
}
.filter-form {
  display: flex;
  flex-wrap: wrap;
}
.table-card {
  margin-bottom: 20px;
}
.table-operations {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}
.total-count {
  margin-right: auto;
  color: #606266;
  font-size: 14px;
}
.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
.inbound-quantity {
  color: #67c23a;
  font-weight: bold;
}
.outbound-quantity {
  color: #f56c6c;
  font-weight: bold;
}
</style> 